package com.mathlearning.auth.service;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.dto.comment.*;
import com.mathlearning.auth.dto.discussion.LikeResponse;
import com.mathlearning.auth.entity.*;
import com.mathlearning.auth.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private CommentLikeRepository commentLikeRepository;

    @Autowired
    private DiscussionRepository discussionRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private DiscussionCacheService cacheService;

    /**
     * 获取讨论的评论列表（顶级评论）
     */
    public CommentListResponse getCommentList(Long discussionId, CommentListRequest request, Long currentUserId) {
        Pageable pageable = PageRequest.of(request.getPage() - 1, request.getPageSize());
        Page<Comment> page;

        if ("latest".equals(request.getSort())) {
            page = commentRepository.findTopCommentsByLatest(discussionId, pageable);
        } else {
            page = commentRepository.findTopCommentsByHot(discussionId, pageable);
        }

        List<CommentResponse> list = page.getContent().stream()
                .map(c -> toCommentResponse(c, currentUserId, false))
                .collect(Collectors.toList());

        return new CommentListResponse(list, page.getTotalElements());
    }

    /**
     * 获取评论的回复列表
     */
    public CommentListResponse getCommentReplies(Long commentId, CommentListRequest request, Long currentUserId) {
        Pageable pageable = PageRequest.of(request.getPage() - 1, request.getPageSize());
        Page<Comment> page = commentRepository.findByParentIdAndIsDeleted(commentId, 0, pageable);

        List<CommentResponse> list = page.getContent().stream()
                .map(c -> toCommentResponse(c, currentUserId, false))
                .collect(Collectors.toList());

        return new CommentListResponse(list, page.getTotalElements());
    }

    /**
     * 发布评论
     */
    @Transactional
    public CommentResponse createComment(Long discussionId, CreateCommentRequest request, Long userId) {
        // 验证讨论是否存在
        Discussion discussion = discussionRepository.findById(discussionId)
                .orElseThrow(() -> new BusinessException("讨论不存在"));

        // 如果是回复，验证父评论是否存在
        if (request.getParentId() != null) {
            Comment parentComment = commentRepository.findById(request.getParentId())
                    .orElseThrow(() -> new BusinessException("父评论不存在"));
            
            // 更新父评论的回复数
            parentComment.setReplies(parentComment.getReplies() + 1);
            commentRepository.save(parentComment);
        }

        // 创建评论
        Comment comment = new Comment();
        comment.setDiscussionId(discussionId);
        comment.setParentId(request.getParentId());
        comment.setAuthorId(userId);
        comment.setContent(request.getContent());
        comment = commentRepository.save(comment);

        // 更新讨论的评论数
        discussion.setComments(discussion.getComments() + 1);
        discussionRepository.save(discussion);

        // 更新缓存中的评论数
        cacheService.updateDiscussionComments(discussionId, discussion.getComments());

        return toCommentResponse(comment, userId, false);
    }

    /**
     * 删除评论
     */
    @Transactional
    public void deleteComment(Long id, Long userId) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new BusinessException("评论不存在"));

        if (!comment.getAuthorId().equals(userId)) {
            throw new BusinessException("无权限删除");
        }

        // 标记为已删除
        comment.setIsDeleted(1);
        commentRepository.save(comment);

        // 更新讨论的评论数
        Discussion discussion = discussionRepository.findById(comment.getDiscussionId()).orElse(null);
        if (discussion != null) {
            discussion.setComments(Math.max(0, discussion.getComments() - 1));
            discussionRepository.save(discussion);
            
            // 更新缓存中的评论数
            cacheService.updateDiscussionComments(comment.getDiscussionId(), discussion.getComments());
        }

        // 如果有父评论，更新父评论的回复数
        if (comment.getParentId() != null) {
            Comment parentComment = commentRepository.findById(comment.getParentId()).orElse(null);
            if (parentComment != null) {
                parentComment.setReplies(Math.max(0, parentComment.getReplies() - 1));
                commentRepository.save(parentComment);
            }
        }
    }

    /**
     * 点赞/取消点赞评论
     */
    @Transactional
    public LikeResponse likeComment(Long id, Long userId) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new BusinessException("评论不存在"));

        boolean isLiked;
        if (commentLikeRepository.existsByCommentIdAndUserId(id, userId)) {
            // 取消点赞
            commentLikeRepository.deleteByCommentIdAndUserId(id, userId);
            comment.setLikes(Math.max(0, comment.getLikes() - 1));
            isLiked = false;
        } else {
            // 点赞
            CommentLike like = new CommentLike();
            like.setCommentId(id);
            like.setUserId(userId);
            commentLikeRepository.save(like);
            comment.setLikes(comment.getLikes() + 1);
            isLiked = true;
        }

        commentRepository.save(comment);
        return new LikeResponse(isLiked, comment.getLikes());
    }

    /**
     * 转换为CommentResponse
     */
    private CommentResponse toCommentResponse(Comment comment, Long currentUserId, boolean includeReplies) {
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setDiscussionId(comment.getDiscussionId());
        response.setParentId(comment.getParentId());
        response.setContent(comment.getContent());
        response.setLikes(comment.getLikes());
        response.setReplies(comment.getReplies());
        response.setCreatedAt(comment.getCreatedAt());

        // 作者信息
        User author = userRepository.findById(comment.getAuthorId()).orElse(null);
        if (author != null) {
            CommentResponse.AuthorInfo authorInfo = new CommentResponse.AuthorInfo();
            authorInfo.setId(author.getId());
            authorInfo.setNickname(author.getNickname());
            authorInfo.setAvatar(author.getAvatar());
            authorInfo.setLocation(null); // 可以从用户信息中获取
            authorInfo.setBadge(null); // 可以从用户信息中获取
            response.setAuthor(authorInfo);
        }

        // 当前用户是否点赞
        if (currentUserId != null) {
            response.setIsLiked(commentLikeRepository.existsByCommentIdAndUserId(comment.getId(), currentUserId));
        } else {
            response.setIsLiked(false);
        }

        // 如果需要包含回复列表
        if (includeReplies && comment.getReplies() > 0) {
            Pageable pageable = PageRequest.of(0, 50);
            Page<Comment> replies = commentRepository.findByParentIdAndIsDeleted(comment.getId(), 0, pageable);
            response.setReplyList(replies.getContent().stream()
                    .map(c -> toCommentResponse(c, currentUserId, false))
                    .collect(Collectors.toList()));
        }

        return response;
    }
}

